package com.icinfo.cloud.provider.punish.common.seal.utils;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.icinfo.cloud.provider.common.dto.OcrData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ocrUtil
 *
 * @author yunchao.peng
 * @create 2023-11-09 19:19
 */
@Slf4j
@Configuration
public class OcrUtil {

    private static final String PROJECT_ID = "bdb866558a6d4bbfaeeb228d8fb662ff";
    private static final String UNIT_ID = "259b6da1-2940-460f-af62-d1c5516d99f6";

    /**
     * 获取api-token
     * 这个是动态token，每个token的有效期为10分钟，（十分钟刷新一次）
     *
     * @return
     */
    private static String getToken() {
        //获取动态token路径
        String url = "23.211.52.151/data_api/dcqc-openapi/v1/openapi/apply/keyToken/c564ea9a7871df72d7d7bbfd19b14a720d1c631a6fc481e63fc0a8d449a833667f123b74ad1e357c1c54f47c49820c82bb2e43750a8f5416c8813df15edf1a82";
        //调用接口
        String request = HttpRequest.get(url).execute().body();
        JSONObject reponseJson = JSON.parseObject(request);
        if(HttpStatus.HTTP_OK != reponseJson.getInteger("code")){
            log.error("重庆获取组件能力token接口异常:"+ request);
            return null;
        }
        JSONObject json = JSON.parseObject(request);
        return json.getString("data");
    }

    /**
     * 获取apiToken
     *
     * @return
     */
    public static String getApiToken() {
        HashMap<String, String> header = getHeader();
        String param = "{\n" +
                "\"auth\": {\n" +
                "\"identity\": {\n" +
                "\"methods\": [\n" +
                "\"hw_ak_sk\"\n" +
                "],\n" +
                "\"hw_ak_sk\": {\n" +
                "\"access\": {\n" +
                "\"key\": \"EKIAZDMHKLEEWO0WPD5V\"\n" +
                "},\n" +
                "\"secret\": {\n" +
                "\"key\": \"B7tiwu2rE22r0CX8gVtQS4p6GcePI9lAcjcfukg7\"\n" +
                "}\n" +
                "}\n" +
                "},\n" +
                "\"scope\": {\n" +
                "\"project\": {\n" +
                "\"id\": \"" + PROJECT_ID + "\"\n" +
                "}\n" +
                "}\n" +
                "}\n" +
                "}";

        String tokenUrl = "http://23.211.52.151/data_api/dcqc-apiserver/gateway/api/baseOpenUrl/aac870a428a54298bc00eb31500c1efe";
        HttpResponse execute = HttpRequest.post(tokenUrl + "?project_id=" + PROJECT_ID + "&unit_id=" + UNIT_ID).addHeaders(header).body(param).execute();
        String request = execute.body();
        JSONObject reponseJson = JSON.parseObject(request);
        if(HttpStatus.HTTP_OK != reponseJson.getInteger("code")){
            log.error("华为获取token接口异常:"+ request);
            return null;
        }
        Map<String, List<String>> headers = execute.headers();
        return headers.get("X-Subject-Token").get(0);
    }

    /**
     * 获取herder
     *
     * @return
     */
    private static HashMap<String, String> getHeader() {
        String api_token = getToken();
        //将请求头参数放入请求头中
        HashMap<String, String> header = new HashMap<>();
        header.put("API-TOKEN", api_token);
        return header;
    }

    /**
     * 获取ocr结果
     *
     * @param file
     * @return
     */
    public static List<OcrData> getOcrData(File file){
        ArrayList<OcrData> ocrData = new ArrayList<>();
        HashMap<String, String> header = getAuthToken();
//        header.put("X-Auth-Token",ocrToken);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("image", Base64.encode(file));
        //调用接口
        String url = "http://23.211.52.151/data_api/dcqc-apiserver/gateway/api/baseOpenUrl/f1072ec567a44969b3912765c0a8509f";
        String  request = HttpRequest.post(url+ "?project_id=" + PROJECT_ID + "&unit_id=" + UNIT_ID).addHeaders(header).body(jsonObject.toString()).execute().body();
//        String request ="{\n" +
//                "    \"explain\":[\n" +
//                "\n" +
//                "    ],\n" +
//                "    \"code\":200,\n" +
//                "    \"data\":\"{\\\"result\\\":[{\\\"name\\\":\\\"彭云超\\\",\\\"sex\\\":\\\"男\\\",\\\"ethnicity\\\":\\\"汉\\\",\\\"birth\\\":\\\"1993-01-06\\\",\\\"address\\\":\\\"河北省石家庄市藁城区兴安镇冯马村北环东路39号\\\",\\\"number\\\":\\\"130182199301060913\\\",\\\"confidence\\\":{\\\"name\\\":0.9086519385842351,\\\"sex\\\":0.8498339653015137,\\\"ethnicity\\\":0.8542070388793945,\\\"birth\\\":0.9062575909555619,\\\"address\\\":0.9151615486615938,\\\"number\\\":0.9117388566012217},\\\"result_type\\\":\\\"id_card_portrait_side\\\"}]}\",\n" +
//                "    \"requestSQL\":\"\",\n" +
//                "    \"message\":\"调用成功!\"\n" +
//                "}";
        JSONObject reponseJson = JSON.parseObject(request);
        if(HttpStatus.HTTP_OK != reponseJson.getInteger("code")){
            log.error("华为ocr接口异常:"+ request);
            return ocrData;
        }
        String data1 = reponseJson.getString("data");
        JSONObject temp = JSONObject.parseObject(data1);
        JSONArray result = temp.getJSONArray("result");
        JSONObject userInfo = result.getJSONObject(0);
        ocrData.add(new OcrData("姓名",userInfo.getString("name")));
        ocrData.add(new OcrData("性别",userInfo.getString("sex")));
        ocrData.add(new OcrData("身份证号",userInfo.getString("number")));
        ocrData.add(new OcrData("出生日期",userInfo.getString("birth")));
        ocrData.add(new OcrData("住址",userInfo.getString("address")));
        return ocrData;
    }

    private static HashMap<String, String> getAuthToken() {
        HashMap<String, String> header = getHeader();
        header.put("X-Auth-Token",getApiToken());
        return header;
    }

    public static void main(String[] args) {
        File file = FileUtil.file("C:\\Users\\hzhb\\Desktop\\e01ed22e76a3e5c28a3a0bd456c483eb.jpg");
        String ocrToken = "MIIDqgYJKoZIhvcNAQcCoIIDmzCCA5cCAQExDTALBglghkgBZQMEAgEwggHmBgkqhkiG9w0BBwGgggHXBIIB03sidG9rZW4iOnsiZXhwaXJlc19hdCI6IjIwMjMtMTEtMTFUMDQ6MTE6NTYuMDkyMDAwWiIsIm1ldGhvZHMiOlsiaHdfYWtfc2siXSwiY2F0YWxvZyI6W10sInJvbGVzIjpbXSwicHJvamVjdCI6eyJkb21haW4i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